<template>
  <div class="login" clearfix>
    <div class="login-wrap">
      <el-row type="flex" justify="center">
        <el-form ref="loginForm" :model="user" status-icon label-width="80px">
          <h3>注册</h3>
          <hr>
          <el-form-item prop="username" label="用户名">
            <el-input v-model="user.username" placeholder="请输入用户名" prefix-icon></el-input>
          </el-form-item>
          <el-form-item id="password" prop="password" label="密码">
            <el-input v-model="user.password" show-password placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item id="rppassword" prop="rppassword" label="重复密码">
            <el-input v-model="user.rppassword" show-password placeholder="请再次输入密码"></el-input>
          </el-form-item>
          <router-link to="/">已有账号，前往登录</router-link>
          <el-form-item>
            <el-button type="primary" icon="el-icon-upload" @click="doLogin()">注 册</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
  </div>
</template>
 
<script>
import { add } from "@/api/user.js";//引入
import { setToken, getToken } from "@/utils/token.js";//引入
export default {
  name: "login",
  data() {
    return {
      user: {
        username: "",
        password: "",
        rppassword: ""
      }  
    };
  },
  created() {
	let token = getToken('token')
	if(token){
		this.$router.push({ path: "/home" });
	}
  },
  methods: {
    doLogin() {
      if (!this.user.username) {
        this.$message.error("请输入用户名！");
        return;
      } else if (!this.user.password) {
        this.$message.error("请输入密码！");
        return;
      } else if (!this.user.rppassword) {
        this.$message.error("请输入确认密码！");
        return;
      }else if(this.user.password != this.user.rppassword){
		  this.$message.error("两次密码不一致！");
		  return;
	  }else {
        //校验用户名和密码是否正确;
        add({
            name: this.user.username,
            password: this.user.password
          })
          .then(res => {
            if (res.code === 200) {
			  this.$message.success("注册成功,前往登录")
              this.$router.push({ path: "/" });
            } else {
              this.$alert("您输入的用户名或密码错误！");
            }
          });
      }
    }
  }
};
</script>
 
<style scoped>
.login {
  width: 100%;
  height:100%;
  background: url("../assets/imgs/bg1.jpg") no-repeat;
  background-size: cover;
  overflow: hidden;
}
.login-wrap {
  background-color: #fff;
  width: 400px;
  height: 380px;
  margin: 215px auto;
  overflow: hidden;
  padding-top: 10px;
  line-height: 40px;
}
h3 {
  color: #0babeab8;
  font-size: 24px;
}
hr {
  background-color: #444;
  margin: 20px auto;
}
a {
  text-decoration: none;
  color: #aaa;
  font-size: 15px;
}
a:hover {
  color: coral;
}
.el-button {
  width: 80%;
  margin-left: -50px;
}
</style>